import type {StaticRouter} from "../../utils";

import {Schema, model} from "mongoose";
import {getFileData} from "../../utils";
import path from "path";

const fs = require("fs");

const authSchema = new Schema({
  roleName: {type: String, required: true, unique: true},
  createTime: {type: Number, default: Date.now()},
  authName: {type: String},
  authTime: {type: Number, default: Date.now()},
  roleList: {type: [Number], require: true, default: []},
  roleDesc: {type: String},
  status: {type: Boolean}
});

const authModel = model("auth", authSchema);

const createCommonRoleList = (staticRouterList: StaticRouter[]) => {
  const list: number[] = [];
  const limit = [3, 4, 5];
  let pidArr: number[] = [];
  staticRouterList.sort((a: StaticRouter, b: StaticRouter) => a.routeId - b.routeId).forEach((route: StaticRouter) => {
    if (limit.indexOf(route.routeId) !== -1) {
      pidArr.push(route.routeId);
    } else {
      if (pidArr.length) {
        if (pidArr.indexOf(route.pid) !== -1 || pidArr.indexOf(route.routeId) !== -1) {
          pidArr.push(route.routeId);
        } else {
          list.push(route.routeId);
        }
      } else {
        list.push(route.routeId);
      }
    }
  });
  return list;

};


const createRole = async () => {
  try {
    const userRoleListStr = await getFileData(path.resolve(process.cwd(), "./src/router/router.json")) as string;
    const userRoleListObj = JSON.parse(userRoleListStr).routerList;
    const userRoleList = [
      {
        roleName: "admin",
        roleList: userRoleListObj.map((route: StaticRouter) => {
          return route.routeId;
        }),
        roleDesc: "测试角色1",
        status: true
      },
      {
        roleName: "common",
        roleList: createCommonRoleList(userRoleListObj),
        roleDesc: "测试角色2",
        status: true
      },
    ];
    for (let i = 0; i < userRoleList.length; i++) {
      const hasRole = await authModel.findOne({roleName: userRoleList[i].roleName});
      if (!hasRole) await authModel.create(userRoleList[i]);
    }
    return true;
  } catch (e) {
    return false;
  }
};

export {
  authModel,
  createRole
};
